package com.university.report.user.service.impl;

import com.university.report.model.entity.Permission;
import com.university.report.model.entity.UserAccount;
import com.university.report.user.mapper.UserAccountMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName health_report
 * @Author Jinondo
 * @Date 2021/6/16 18:00
 */
@Component
@Slf4j
public class MemberUserDetailsService implements UserDetailsService {
    @Autowired
    UserAccountMapper userAccountMapper;

    @SneakyThrows
    @Override
    public UserDetails loadUserByUsername(String username) throws AuthenticationException {
        // 1.根据该用户名称查询在数据库中是否存在
        UserAccount userAccount = userAccountMapper.selectByUsername(username);
        if (userAccount == null) {
            return null;
        }
        // 2.查询对应的用户权限
        List<Permission> listPermission = userAccountMapper.findPermissionByUsername(username);
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        listPermission.forEach(user -> {
            authorities.add(new SimpleGrantedAuthority(user.getPermTag()));
        });
        log.info(">>>authorities:{}<<<", authorities);
        // 3.将该权限添加到security
        userAccount.setAuthorities(authorities);
        return userAccount;
    }
}
